#include "comm.hpp"

// shm通信是ipc中最快的
// shm的使用是比较随意地，并没有类似于管道的同步机制，但是进程间通信是需要一种同步机制的,但是可以借助管道来实现同步机制


//利用对象的生命周期
class Init
{
public:
    Init()
    {
        key_t key = GetKey();
        cout << "key : " << ToHex(key) << endl;
        // sleep(3);
        shmid = CreateShm(key);
        cout << "创建共享内存成功 ！"
             << " shm:" << shmid << endl;
        // sleep(5);
        //  挂接
        s = (char *)shmat(shmid, nullptr, 0);
        cout << "共享内存挂接成功 ！ : " << (void *)s << endl;
        Createfifo();
         fd = open(filename, O_RDONLY);
    }
    ~Init()
    {
        //获取shm的属性struct
        // struct shmid_ds ds;
        // shmctl(shmid,IPC_STAT,&ds);
        // cout<< ToHex(ds.shm_perm.__key)<<endl;
        // cout<< ToHex(ds.shm_cpid)<<endl;
        // cout<< ToHex(ds.shm_ctime)<<endl;
        // cout<< ToHex(ds.shm_nattch)<<endl;
        // sleep(4);
        // sleep(7);
        DeleteShm(s);
        cout << "解挂成功 ！" << endl;
        // sleep(6);
        CleanShm(shmid);
        cout << "共享内存清除成功 ！" << endl;
    }

public:
    int fd;
    int shmid;
    char *s;
};

int main()
{

    Init init;
    
    while (true)
    {
        int code = 0;
        ssize_t si = read(init.fd, &code, sizeof(code));
        if (si > 0)
        {
            cout << "say#_" << code << ": " << init.s << endl;
        }
        else if (si == 0)
        {
            break;
        }
        sleep(1);
    }
    return 0;
}
